package com.chechi.server.util;

import com.chechi.server.common.Constant;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.glassfish.jersey.client.JerseyClient;
import org.glassfish.jersey.client.JerseyClientBuilder;
import org.glassfish.jersey.client.JerseyWebTarget;
import org.glassfish.jersey.media.multipart.MultiPartFeature;


import javax.net.ssl.*;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.Invocation;
import javax.ws.rs.core.*;
import java.security.KeyManagementException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by nemo8 on 2016/8/11.
 */
public final class JerseyUtils {
    private static JsonNodeFactory factory = new JsonNodeFactory(false);
    private static final char[] HEX_DIGITS = {'0', '1', '2', '3', '4', '5',
            '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

    /**
     * Send Https Post Requests with Jersey
     */
    public static ObjectNode sendRequest(JerseyWebTarget jerseyWebTarget, Object body) {
        ObjectNode objectNode = factory.objectNode();

        try {
            List<NameValuePair> headers = getHeaders();
            Invocation.Builder inBuilder = jerseyWebTarget.request();
            headers.stream().forEach(nameValuePair -> inBuilder.header(nameValuePair.getName(), nameValuePair.getValue()));
            Response response;

            response = inBuilder.post(Entity.entity(body, MediaType.APPLICATION_FORM_URLENCODED_TYPE), Response.class);
            objectNode = response.readEntity(ObjectNode.class);
            /*MultivaluedMap header= response.getHeaders();
            for (Object o : header.entrySet()) {
                Map.Entry entry = (Map.Entry) o;
                objectNode.put(entry.getKey().toString(), ((List<Object>) entry.getValue()).get(0).toString());
            }*/
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        return objectNode;
    }


    /**
     * check url
     *
     * @param regex
     * @param str
     * @return
     */
    public static boolean match(String regex, String str) {
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(str);
        return matcher.lookingAt();
    }

    private static List<NameValuePair> getHeaders() {
        String Nonce = Integer.toString((new SecureRandom()).nextInt(100000));
        String CurTime = String.valueOf(System.currentTimeMillis() / 1000L);
        String CheckSum = getCheckSum(Constant.APP_SECRET, Nonce, CurTime);
        List<NameValuePair> headers = new ArrayList<>();
        headers.add(new BasicNameValuePair("AppKey", "36970d441935854fa2928018ac3a2c31"));
        headers.add(new BasicNameValuePair("Nonce", Nonce));
        headers.add(new BasicNameValuePair("CurTime", CurTime));
        headers.add(new BasicNameValuePair("CheckSum", CheckSum));
        headers.add(new BasicNameValuePair("Content-Type", "application/x-www-form-urlencoded;charset=utf-8"));
        return headers;
    }


    private static String getCheckSum(String appSecret, String nonce, String curTime) {
        return encode("sha1", appSecret + nonce + curTime);
    }


    // 计算并获取md5值
    public static String getMD5(String requestBody) {
        return encode("md5", requestBody);
    }

    private static String encode(String algorithm, String value) {
        if (value == null) {
            return null;
        }
        try {
            MessageDigest messageDigest
                    = MessageDigest.getInstance(algorithm);
            messageDigest.update(value.getBytes());
            return getFormattedText(messageDigest.digest());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private static String getFormattedText(byte[] bytes) {
        int len = bytes.length;
        StringBuilder buf = new StringBuilder(len * 2);
        for (int j = 0; j < len; j++) {
            buf.append(HEX_DIGITS[(bytes[j] >> 4) & 0x0f]);
            buf.append(HEX_DIGITS[bytes[j] & 0x0f]);
        }
        return buf.toString();
    }


    public static JerseyClient getJerseyClient(boolean isSSL, Configuration config) {
        ClientBuilder clientBuilder = JerseyClientBuilder.newBuilder().withConfig(config).register(MultiPartFeature.class);

        // Create a secure JerseyClient
        if (isSSL) {
            try {
                HostnameVerifier verifier = new HostnameVerifier() {
                    public boolean verify(String hostname, SSLSession session) {
                        return true;
                    }
                };

                TrustManager[] tm = new TrustManager[]{new X509TrustManager() {

                    public X509Certificate[] getAcceptedIssuers() {
                        return null;
                    }

                    public void checkServerTrusted(X509Certificate[] chain, String authType)
                            throws CertificateException {
                    }

                    public void checkClientTrusted(X509Certificate[] chain, String authType)
                            throws CertificateException {
                    }
                }};

                SSLContext sslContext = sslContext = SSLContext.getInstance("SSL");

                sslContext.init(null, tm, new SecureRandom());

                clientBuilder.sslContext(sslContext).hostnameVerifier(verifier);
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            } catch (KeyManagementException e) {
                e.printStackTrace();
            }
        }

        return (JerseyClient) clientBuilder.build().register(JacksonJsonProvider.class);
    }
}
